import { defineStore } from "pinia";
import { ref } from "vue";
import { fetchMessageListAPI, messageReadAllAPI, messageReadAPI } from "@/api/messageApi";

const useMessageStore = defineStore("messageStore", () => {
  const counts = ref(0);
  /*通知列表*/
  const messageList = ref([]);
  const pages = ref(0);
  /*公告列表*/
  const announceList = ref([]);

  /*获取通知列表的请求函数*/
  const fetchMessageList = async (params) => {
    const { data } = await fetchMessageListAPI(params);
    counts.value = data.counts;
    messageList.value.push(...data.items);
    params.page++;
  };
  /*获取公告列表的请求函数*/
  const fetchAnnounceList = async (params) => {
    const { data } = await fetchMessageListAPI(params);
    pages.value = data.pages;
    announceList.value.push(...data.items);
    params.page++;
  };

  /*全部已读的请求函数*/
  const messageReadAll = async (contentType) => {
    await messageReadAllAPI(contentType);
    if (contentType === 201) {
      messageList.value.forEach(item => item.isRead = 1);
    } else {
      announceList.value.forEach(item => item.isRead = 1);
    }
  };

  /*标记已读的请求函数*/
  const messageRead = async (contentType, id) => {
    await messageReadAPI(id);
    if (contentType === 201) {
      const message = messageList.value.find(item => item.id === id);
      message.isRead = 1;
    } else {
      const announce = announceList.value.find(item => item.id = id);
      announce.isRead = 1;
    }
  };

  return {
    counts,
    messageList,
    pages,
    announceList,
    fetchMessageList,
    fetchAnnounceList,
    messageReadAll,
    messageRead,
  };
});

export default useMessageStore;
